package com.chatroomdemo.controller;

import com.chatroomdemo.model.MessageSession;
import com.chatroomdemo.model.MessageSessionUser;
import com.chatroomdemo.service.MessageService;
import com.chatroomdemo.service.SessionService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/session")
@Slf4j
public class SessionController {
    @Autowired
    private SessionService sessionService;


    /**
     * @author 陈嘉宇
     * 获取会话列表
     * @see MessageSession
     * @param
     * @param
     * @return List<MessageSession>
     */
    @RequestMapping("/getSessionList")
    public List<MessageSession> getSessionList(HttpSession session){
        if(session==null){
            log.info("用户未登录!");
            return new ArrayList<MessageSession>();
        }
        Integer userId =(Integer)session.getAttribute("session_userId");
        if(userId==null || userId < 0){
            log.info("当前用户信息不存在!");
            return new ArrayList<MessageSession>();
        }
        List<MessageSession> messageSessionList = new ArrayList<>();
        return sessionService.getSessionList(userId);
    }

    /**
     * @author 陈嘉宇
     * 点击好友列表创建会话
     * @param 
     * @param 
     * @return 
     */
    @Transactional//开启事务
    @RequestMapping("/getSessionByClickFriend")
    public Object getSessionByClickFriend(Integer toUserId , HttpSession session){
        Map<String,Integer> returnMap = new HashMap<>();
        if (session == null) {
            log.info("未获取到用户信息");
            return -1;
        }
        Integer userId = (Integer) session.getAttribute("session_userId");
        if(userId == null) {
            log.info("userId 为空");
            return -1;
        }

        MessageSession messageSession = new MessageSession();
        sessionService.insertMessageSession(messageSession);

        MessageSessionUser messageSessionUser1 = new MessageSessionUser(messageSession.getSessionId(), toUserId);
        MessageSessionUser messageSessionUser2 = new MessageSessionUser(messageSession.getSessionId(), userId);
        sessionService.insertMessageSessionUser(messageSessionUser1);
        sessionService.insertMessageSessionUser(messageSessionUser2);

        log.info("新增会话，sessionId:" + messageSession.getSessionId());

        returnMap.put("sessionId", messageSession.getSessionId());
        return returnMap;
    }
}
